<template>
    <div class="e-form">
        <div class="tabs warningTabs">
            <el-tabs
                tab-position="left"
                v-model="tabsName"
                @tab-click="onChangeTab"
            >
                <el-tab-pane
                    label="基本信息"
                    name="baseInfo"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="物资明细"
                    name="detailed"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="附件信息"
                    name="attach"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="审核历史"
                    name="auditHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>
                <el-tab-pane
                    label="变更历史"
                    name="changeHistory"
                    :disabled="clickTabFlag"
                ></el-tab-pane>

                <div>
                    <div id="baseInfoCon" class="con">
                        <div class="tabs-title" id="baseInfo">基本信息</div>
                        <div style="width: 100%" class="form">
                            <el-form :model="basicForm" :label-width="formLabelWidth"
                               ref="ruleForm"
                             :rules="rules"
                             class="demo-ruleForm"
                            >
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="计划编号：">
                                    <span>{{ basicForm.billNo }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                 <el-form-item label="年度需用计划：" prop="annualDemandPlanBillId">
                                         <el-input v-model="basicForm.annualDemandPlanBillNo" readonly>
                                                <i slot="suffix" class="el-input__icon el-icon-document-copy"  @click="clickSelecYear" ></i>

                                        </el-input>
                                           <el-button style="width: 100px"
                                            @click="clickToYearNeedPlan"
                                            >查看</el-button
                                        >

                                        <!-- <IntroductionAnnualPlan @yearPlanObj="getYearPlanObj" :billObj.sync="billObj1"></IntroductionAnnualPlan> -->
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="采购人：" prop="purchaserName">
                                    <el-input v-model="basicForm.purchaserName" readonly>
                                                <i slot="suffix" class="el-input__icon el-icon-document-copy"  @click="clickSelectName" ></i>

                                    </el-input>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="计划日期：" prop="planDate">
                                    <el-date-picker
                                        value-format="yyyy-MM-dd"
                                        :clearable="false"
                                        type="date"
                                        placeholder="选择日期"
                                        v-model="basicForm.planDate"
                                    ></el-date-picker>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>

                            <el-col :span="12">
                                <el-form-item label="单据机构：">
                                    <span>{{ basicForm.orgName }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                           <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="税率%："
                                            prop="taxRate"
                                        >
                                            <el-input
                                                v-enter-integer2="{
                                                set:this,
                                                val:'basicForm',
                                                key:'taxRate'
                                                }"
                                                @input="onTaxRate"
                                                v-model="basicForm.taxRate"
                                            ></el-input>
                                        </el-form-item>
                                    </el-col>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="税额："
                                            prop="taxAmount"
                                        >

                                            <el-input
                                            @input="onTaxRate('taxAmount')"
                                            v-enter-float="{
                                            set:this,
                                            val:'basicForm',
                                            key:'taxAmount'
                                            }"
                                            v-model="basicForm.taxAmount"
                                        ></el-input>
                                        </el-form-item>
                                    </el-col>
                                </el-row>
                                <el-row>
                                    <el-col :span="12">
                                        <el-form-item
                                            label="不含税计划金额（元）："
                                            ><span>
                                                {{
                                                    basicForm.amountExcludingTax
                                                }}
                                            </span>
                                        </el-form-item>

                                    </el-col>
                                    <el-col :span="12">
                                <el-form-item label="计划金额（元）：">
                                    <template>
                                        {{
                                            basicForm.amount
                                        }}
                                    </template>

                                </el-form-item>
                            </el-col>
                                </el-row>
                        <el-row>
                            <el-col :span="12">
                                 <el-form-item
                                            label="币种："
                                        >
                                            <span>
                                {{
                                   basicForm.currency
                                }}
                            </span>
                                        </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="人民币汇率：">
                                    <span>{{ basicForm.rmbRate }}</span>

                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="变更期数：">
                                    <span>{{ basicForm.period }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item label="状态：">
                                    <span>{{ statusLable(basicForm.state) }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="24">
                                <el-form-item label="备注：">
                                    <el-input
                                        type="textarea"
                                        v-model="basicForm.remarks"
                                        autocomplete="off"
                                    ></el-input>
                                </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="本位币：">
                                    <span>{{ basicForm.baseCurName }}</span>
                                </el-form-item>
                            </el-col>
                            <el-col :span="12">
                                <el-form-item
                                            label="本位币汇率："
                                            v-if="showBaseCurName"
                                            prop="baseCurRate"
                                        >
                                            <el-input
                                                v-enter-float1="{
                                                    set: this,
                                                    val: basicForm,
                                                    key: baseCurRate
                                                }"
                                                v-model="basicForm.baseCurRate"
                                            ></el-input>
                                        </el-form-item>
                            </el-col>
                        </el-row>
                        <el-row>
                            <el-col :span="12">
                                <el-form-item label="填报人：">
                                    <span>{{ basicForm.preparer }}</span>
                                </el-form-item>
                            </el-col>
                        </el-row>

                    </el-form>
                        </div>
                    </div>
                    <!-- 物资明细 -->
                    <div id="detailedCon" class="con">
                        <div class="tabs-title" id="detailed">物资明细</div>
                        <div class="e-table">
                            <div class="top">
                                <div class="left">
                                    <el-button size="mini" type="primary"
                                     @click="clickYearNeedPlanImport"
                                        >年计划引入</el-button
                                    >
                                </div>
                            </div>
                             <div class="errorMsg" v-if="errorMsg.length > 0">
                                <span
                                    v-for="(item, index) in errorMsg"
                                    :key="index"
                                >
                                    {{ item }}
                                </span>
                            </div>
                            <el-table
                                      class="table"
                                :data="detailedTableDataComputed"
                                border
                                style="width: 100%"
                                 default-expand-all
                                :header-cell-style="{ textAlign: 'center' }"
                                :cell-style="{ textAlign: 'center' }"
                                :tree-props="{
                                    children: 'children',
                                    hasChildren: 'hasChildren'
                                }"
                                ref="multipleTable"
                                row-key="uuid"
                                 :max-height="$store.state.tableHeight"
                                 :row-class-name="tableRowClassName"
                                 v-sortTable="{ 'tableData': detailedTableDataComputed, '_this': this, 'ref': 'multipleTable' }"
                            >
                               <el-table-column
                                    label="操作"
                                    fixed
                                    width="100px"
                                    align="left"
                                >

                 <template slot-scope="{ row, $index }">
                                        <div class="handle">
                                            <div style="cursor: pointer">
                                                <img
                                                v-if="$index > 0"
                                                    src="@/assets/btn/delete.png"
                                                    @click="
                                                        deleteEle(
                                                            row,
                                                            $index
                                                        )
                                                    "
                                                />
                                            </div>
                                        </div>
                                    </template>

                                </el-table-column>
                                <el-table-column
                                    prop="materialClassName"
                                    label="类别"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="materialName"
                                    label="物资名称"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="spec"
                                    label="规格"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="unit"
                                    label="计量单位"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    prop="texture"
                                    label="材质"
                                    width="200"
                                >

                                </el-table-column>

                                <el-table-column
                                    prop="quantity"
                                    label="需求数量"
                                    width="200"
                                >
                                 <template slot-scope="{ row, $index }">
                                        <el-input
                                            @input="curStateChange(row)"
                                        v-enter-float2="{
                                            set: row,
                                            key: 'quantity'
                                        }"
                                            v-model="row.quantity"
                                            clearable
                                            v-if="$index > 0"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="price"
                                    label="单价（元）"
                                    width="200"
                                >
                                     <template slot-scope="{ row, $index }">
                                        <el-input
                                            @input="curStateChange(row)"
                                    v-enter-float="{
                                            set: row,
                                            key: 'price'
                                        }"
                                            v-model="row.price"
                                            clearable
                                            v-if="$index > 0"
                                        ></el-input>
                                    </template>
                                </el-table-column>
                                <el-table-column
                                    prop="amount"
                                    label="金额（元）"
                                    width="200"
                                >
                                <template slot-scope="{row,$index}">
                                    <span v-if="$index>0">
                                        {{
                                            row.amount
                                        }}
                                    </span>
                                </template>
                                </el-table-column>

                                <el-table-column
                                    prop="startTime"
                                    label="预计进场时间"
                                    width="200"
                                >
                                  <template slot-scope="{row, $index }">
                                     <el-date-picker
                                                 @change="curStateChange(row)"
                                                v-if="$index>0"
                                                type="date"
                                                placeholder="选择日期"
                                                value-format="yyyy-MM-dd"
                                                v-model="row.startTime"
                                            ></el-date-picker>
                                </template>
                                </el-table-column>

                            </el-table>

                        </div>
                    </div>
                    <!-- 附件信息 -->
                    <div id="attachCon" class="con">
                        <div class="tabs-title" id="attach">附件信息</div>
                    <attach-comp :relationId="attachId" bucketName="turnover" />
                    </div>
                    <!-- 审核历史 -->
                    <div id="auditHistoryCon" class="con">
                        <div class="tabs-title" id="auditHistory">审核历史</div>
                        <div class="e-table">
                            <ComAuditHistoryIndex
                                :billType="6088"
                                ref="AuditHistoryRef"
                            />
                        </div>
                    </div>
                    <!-- 变更历史 -->
                    <div id="changeHistoryCon" class="con">
                        <div class="tabs-title" id="changeHistory">
                            变更历史
                        </div>
                        <div class="e-table">
                               <el-table
                                :data="changeTableData"
                                border
                                style="width: 100%"
                            >
                                <el-table-column
                                    prop="period"
                                    label="变更期数"
                                    width="200"
                                >
                                </el-table-column>
                                <el-table-column
                                    fixed
                                    label="变更编号"
                                    min-width="250"
                                >
                                    <template slot-scope="scope">
                                        <span
                                            style="color: blue"
                                            @click="tableDbShow(scope.row)"
                                            >{{ scope.row.billNo }}</span
                                        >
                                    </template>
                                </el-table-column>
                                  <el-table-column
                                    prop="planDate"
                                    label="变更日期"
                                    width="200"
                                >
                                </el-table-column>

                                  <el-table-column
                                    prop="amount"
                                    label="原计划金额"
                                    width="200"
                                >
                                </el-table-column>
                                  <el-table-column
                                    prop="amountChange"
                                    label="变更金额"
                                    width="200"
                                >
                                </el-table-column>
                                  <el-table-column
                                    prop="amountChanged"
                                    label="变更后计划金额"
                                    width="200"
                                >
                                </el-table-column>

                                <el-table-column
                                    prop="state"
                                    label="状态"
                                    width="200"
                                >
                                    <template slot-scope="scope">
                                        <span>{{
                                            statusLable(scope.row.state)
                                        }}</span>
                                    </template>
                                </el-table-column>
                            </el-table>
                        </div>
                    </div>
                </div>
            </el-tabs>
        </div>
             <div class="buttons">
            <span class="tip"><span style="color: red; margin-right: 0">*</span>为必填项</span>

            <ComExaButtons :auditState="auditState" :state="basicForm.state" @exas="exas" :founderId="basicForm.founderId" />
            <el-button size="small" @click="handleClose">关闭</el-button>
        </div>
        <div id="seat" :style="{ height: seatHeight + 'px' }"></div>
    </div>
</template>

<script>
import AttachComp from '@/components/common/attachIndex'
import ComAuditHistoryIndex from '@/pages/revolveMaterialManage/components/auditHistory/auditHistoryIndex'

import ComExaButtons from '@/components/common/exaButtons'
import { exas, saveAll, submitCommit, deleteLogic, detailedTableDataComputed  } from '@/pages/revolveMaterialManage/common/revolveCom.js'
import auditRequest from '@/api/turnover/audit.js'
import planRequest from '@/api/turnover/plan.js'
import { mapMutations } from 'vuex'
import $ from 'jquery'
import '@/utils/jquery.scrollTo.min'
import { mapState } from 'vuex'
import { getRmbRate } from '@/api/equip/common.js'
import {  getUuid, openAppClient, showLoading, hideLoading } from '@/utils/common'
import {  introducePlan, selectName, setYearPlanData } from '@/api/turnover/ppw.js'
export default {
    components: {
        AttachComp,
        ComAuditHistoryIndex,
        ComExaButtons
    },
    computed: {
        // 填补底部空白，以使高度够滚动
        seatHeight () {
            return this.screenHeight - 72 - this.lastConHeight
        },
        attachId () {
            return this.id
        },
        ...mapState({
            userInfo: state => state.userInfo,
            currencyForm: state => state.equip.equipData.currencyForm, //币种
            timeUnitList: state => state.equip.equipData.timeUnitList //计时单位
        }),
        statusLable () {
            return param => {
                const state = this.$store.state.equip.equipData.state
                const obj = state.find(x => x.value === param)
                if (obj !== undefined) {
                    return obj.label
                }
            }
        },
        billObj1 () {
            return {
                annualDemandPlanBillNo: this.basicForm.annualDemandPlanBillNo,
                annualDemandPlanBillId: this.basicForm.annualDemandPlanBillId
            }
        },
        detailedTableDataComputed () {
            return detailedTableDataComputed(this.detailedTableData)
        }
    },
    watch: {
        //给错误标签加上提醒
        errorList: newData=>{
            const tabs = document.querySelectorAll('.el-tabs__item')
            tabs.forEach(DOM=>{
                const { childNodes } = DOM
                if(childNodes.length > 1) {
                    DOM.removeChild(childNodes[1])
                }
            })
            newData.forEach(item=>{
                const itemDom = document.querySelector(`#tab-${item}`)
                var element = document.createElement('i')
                element.className = 'el-icon-warning-outline warning'
                itemDom.appendChild(element)
            })
        },
    },
    mounted () {
        this.getLastConHeight()
        // 保存所有tabName
        const arr = [
            'baseInfo',
            'detailed',
            'attach',
            'auditHistory',
            'changeHistory'
        ]
        this.tabArr = arr  //标星星

        let $idsTop = []
        window.addEventListener('scroll', () => {
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            if (this.clickTabFlag) {
                return
            }

            if (!$idsTop[$idsTop.length - 1]) {
                $idsTop = arr.map(item => {
                    const itemTop = document.getElementById(item).offsetTop
                    return itemTop
                })
            }
            const scrollTop =
                document.documentElement.scrollTop || document.body.scrollTop
            // 倒序查找
            let curLocal = 0
            for (let len = $idsTop.length, i = len - 1; i >= 0; i--) {
                let item = $idsTop[i]
                if (scrollTop + 1 >= item) {
                    curLocal = i
                    break
                }
            }
            // 设置对应tabName
            this.tabsName = arr[curLocal]
        })
        this.screenWidth = document.documentElement.clientWidth - this.topHeight
        this.screenHeight = document.documentElement.clientHeight - this.topHeight
        window.addEventListener('resize', () => {
            this.screenWidth = document.documentElement.clientWidth - this.topHeight
            this.screenHeight = document.documentElement.clientHeight - this.topHeight
            $idsTop = arr.map(item => {
                const itemTop = document.getElementById(item).offsetTop
                return itemTop
            })
        })
        this.scorllDtl()
    },
    created () {
        this.id = this.$route.query.billid
        this.getCurrentUnitInfo()

        this.getBasicInfo()
        this.getUserInfo()
        this.getYearNeedPlanList()
        // this.getChengeTableData()

        this.initData()
    },
    data () {
        return {
            tabsName: 'baseInfo',
            screenWidth: 0,
            screenHeight: 0,
            lastConHeight: 0,
            clickTabFlag: false, // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            basicForm: {
                'amount': 0,
                'annualDemandPlanBillId': '',
                'annualDemandPlanBillNo': '',
                'baseCurAmt': 0,
                'baseCurId': '',
                'baseCurName': '',
                'baseCurRate': 0,
                'billId': '',
                'billNo': '',
                'currency': '',
                'currencyId': '',
                'nullifyCreated': '',
                'nullifyCreator': '',
                'nullifyCreatorId': '',
                'nullifyDescription': '',
                'nullifyReason': '',
                'period': 0,
                'planDate': '',
                'preparer': '',
                'preparerId': '',
                'purchaserId': '',
                'purchaserName': '',
                'remarks': '',
                'rmbId': '',
                'rmbName': '',
                'rmbRate': 0,
                'state': '',
                'workId': '',
                'taxAmount': '',
                'taxRate': '',
                'amountExcludingTax': null, //不含税计划金额
            },
            formLabelWidth: '180px',
            detailedTableData: [], //物资明细

            detailedTableDataCopy: [], //发送给数据库的明细
            tableData: [],
            changeTableData: [],
            basicInfo: {},
            query: {
                limit: 10,
                number: '',
                orgname: '',
                page: 1,
                states: [],
            },
            MouseEnterId: 0,
            stateArr: ['草稿', '审核中', '已审核', '已作废'],
            currencyArr: [], //币种列表
            yearNeedPlanList: [],
            auditState: {},
            auditParams: {
                billId: this.$route.query.billid,
                billType: 6088,
                freeNextUnitIndex: 0,
                freeNextUser: '',
                isPass: true,
                isShareInAudit: true,
                opinion: ''
            },
            errorList: [], //控制导航栏感叹号的显示
            errorMsg: [],
            isErrorMsg: true, //是否提醒错误信息
            rules: {
                planDate: [
                    {
                        required: true,
                        message: '请输入计划日期',
                        trigger: 'blur'
                    }
                ],
                currencyId: [
                    { required: true, message: '请选择币种', trigger: 'change' }
                ],
                taxRate: [
                    { required: true, message: '请填写税率', trigger: 'blur' }
                ],
                taxAmount: [
                    { required: true, message: '请填写税额', trigger: 'blur' }
                ],
                purchaserName: [
                    { required: true, message: '请填写采购人', trigger: 'blur' }
                ],
                annualDemandPlanBillId: [
                    { required: true, message: '请选择年计划', trigger: 'change' }
                ],

                amount: [
                    {
                        required: true,
                        message: '请填写计划金额',
                        trigger: 'blur'
                    }
                ]
            },
            itemObj: {},
            showBaseCurName: false

        }
    },
    methods: {
        ...mapMutations(['setAuditParams', 'setSelectedInfo']),
        initData () {
            this.getDtlList()
        },
        //跳转到明细
        scorllDtl () {
            if(this.$route.query.name) {
                setTimeout(() => {
                    //因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                    let obj = {
                        name: this.$route.query.name
                    }
                    this.tabsName = this.$route.query.name
                    this.onChangeTab(obj)
                }, 200)
            }
        },
        getDtlList () {
            planRequest.turnoverProcurementPlanFindDtlByBillId(this.id).then(res=>{
                res.forEach(item=>{
                    const count = item.children.reduce(
                        (prev, c) => (prev += c.amount || 0),
                        0
                    )
                    item.materialName = `小计： ${count}`

                    item.uuid = getUuid()

                    item.materialClassName = item.topClassName
                    item.children.forEach(v=>{
                        v.uuid = getUuid()
                        v.parentId = item.uuid
                    })
                })

                this.detailedTableData = res

                this.collectCount()
                this.onTaxRate()
            })
        }
        ,
        onChangeTab (e) {
            const height  = $('#' + e.name).offset().top
            $.scrollTo(height - this.topHeight, 500)
            // 如果手动点击时，则不做滚动事件逻辑，只有滚动屏幕时才走滚动事件逻辑
            this.clickTabFlag = true
            // 动画结束后，恢复状态
            setTimeout(() => {
                this.clickTabFlag = false
            }, 600)
        },
        // 获取最后一个内容区域的高度，计算底部空白
        getLastConHeight () {
            let si = setInterval(() => {
                // 因为dom异步加载，通过轮询找到渲染后的dom，获取高度
                if (document.getElementById('recodesCon')) {
                    const lastConHeight =
                        document.getElementById('recodesCon').offsetHeight
                    console.log('lastConHeight: ', lastConHeight)
                    this.lastConHeight = lastConHeight
                    clearInterval(si)
                    si = null
                }
            }, 100)
        },
        //获取本地登录信息
        getUserInfo () {
            const userInfo = JSON.parse(window.localStorage.getItem('vuex')).userInfo.orgInfo
            const { baseCyByOrgId } = this.userInfo

            this.basicForm.baseCurName = baseCyByOrgId.currencyName  //本位币
            this.basicForm.baseCurId = baseCyByOrgId.currency
            this.basicForm.orgId = userInfo.orgId
            this.basicForm.orgName = userInfo.orgName
        },
        getYearNeedPlanList () {
            this.$Ajax
                .httpPost({
                    url: '/turnover/annualDemandPlan/listByEntity',
                    params: this.query
                })
                .then(res => {
                    this.yearNeedPlanList = res.list
                })
        },
        //币种切换
        currencyChange (val) {
            this.basicForm.currency = this.currencyForm.find(
                x => x.value === val
            ).label //币种
            if (this.basicForm.currency === '人民币') {
                this.basicForm.rmbRate = 1
            } else {
                getRmbRate({
                    //获取机构下某币种的人民币汇率
                    currency: val,
                    orgId: this.userInfo.orgInfo.orgId
                })
                    .then(res => {
                        this.basicForm.rmbRate = res.rate
                    })
                    .catch(() => {})
            }
            if (this.basicForm.currencyId === this.basicForm.baseCurId) {
                //币种=本位币
                this.basicForm.baseCurRate = 1
                this.showBaseCurName = false
            } else {
                this.basicForm.baseCurRate = null
                this.showBaseCurName = true
            }
        },
        getBasicInfo () {
            this.$Ajax
                .httpGet({
                    url: '/turnover/procurementPlan/findById',
                    params: {
                        billId: this.id
                    },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(res => {
                    for (let key in res) {
                        this.basicForm[key] = res[key]
                    }

                })
        },
        getChengeTableData () {
            this.$Ajax
                .httpPost({
                    url: '/turnover/procurementPlanChanged/listByEntity',
                    params: this.query,
                })
                .then(res => {
                    this.changeTableData = res.list
                })
        },
        // 获取年计划明细数据
        async clickSelecYear () {
            const obj = await introducePlan()
            this.basicForm.annualDemandPlanBillNo = obj.billNo
            this.basicForm.annualDemandPlanBillId = obj.billId

            this.basicForm.currency = obj.currency
            this.basicForm.currencyId = obj.currencyId
            planRequest.turnoverProcurementPlanUpdate(this.basicForm) //先保存
        },
        clickToYearNeedPlan () {
            let billid = this.basicForm.annualDemandPlanBillId
            if (!billid) {
                this.clientPop('err', '请选择年度需用计划！')
                return
            }
            // 客户端弹窗弹出本地页面
            openAppClient(`/yearNeedPlanShow?billid=${billid}&isview=true`, '年度需用计划')
        },
        //引入年计划
        async clickYearNeedPlanImport () {
            setYearPlanData(this.detailedTableData, this.basicForm.annualDemandPlanBillId, this.id, 1, 'procuremenPlan').then(res=>{
                this.detailedTableData = res.detailedTableData
                this.collectCount()
                this.onTaxRate()

            })
        },
        // 选择人员
        async clickSelectName () {
            const obj = await selectName() //选人员弹窗
            this.basicForm.purchaserName = obj.userName //采购人
            this.basicForm.purchaserId = obj.userId
        },
        //判断当前状态是否已修改
        curStateChange (row) {
            this.numYuan(row)
            if (row.dtlId) {
                row.changeType = 2
            }

        },
        //小计明细金额
        numYuan (row) {

            if(row.quantity && row.price ) {
                row.amount = Number(row.quantity * row.price).toFixed(2)
            }
            this.collectCount()
            this.onTaxRate()

        },
        //明细金额向上汇总到基础表单 不含税计划金额（元）
        collectCount () {
            this.basicForm.amountExcludingTax = 0
            this.detailedTableData.forEach(v => {
                v.children.forEach(item => {
                    if (item.changeType != -1) {
                        this.basicForm.amountExcludingTax += Number(item.amount)
                    }
                })
                const count = v.children.reduce(
                    (prev, c) => (prev += Number(c.amount) || 0),
                    0
                ).toFixed(2)
                v.materialName = `小计： ${count}`
            })
        },
        //税率失去焦点的时候 计算 税额 = 不含税计划金额（元）*税率%
        onTaxRate (curInputValue = '') {
            if (
                this.basicForm.amountExcludingTax !== null &&
            this.basicForm.taxRate !== null
            ) {
                if(curInputValue !== 'taxAmount') {
                    // 税额
                    this.basicForm.taxAmount =
                Number((this.basicForm.amountExcludingTax * this.basicForm.taxRate) / 100).toFixed(2)
                }

                // 计划金额
                this.basicForm.amount =
              (Number(this.basicForm.taxAmount) + Number(this.basicForm.amountExcludingTax)).toFixed(2)

            }
        },
        /**
         * 审核
         */
        getCurrentUnitInfo () {
            auditRequest.getCurrentUnitInfo(this.auditParams).then(res => {
                this.auditState = res
            })
        },
        //更新基本信息
        updateBaseInfo () {
            return new Promise((resolve, reject)=>{
                this.$refs.ruleForm.validate(valid => {
                    if (valid) {
                        planRequest.turnoverProcurementPlanUpdate(this.basicForm).then(()=>{
                            this.getBasicInfo() //更新基本信息
                            resolve()
                        }).catch(err=>{
                            this.setError('baseInfo')
                            reject(err)
                        })
                    }
                    else {
                        this.setError('baseInfo')
                        this.scorllError()
                        return false
                    }
                })
            })
        },
        //更新计划明细
        updateBudgetDtl () {
            if(this.detailedTableData.length == 0) return
            return new Promise((resolve, reject)=>{
                this.verifyTable().then(()=>{
                    planRequest.turnoverProcurementPlanUpdateDtl(this.detailedTableData).then(()=>{
                        this.getDtlList() //更新明细
                        resolve()
                    }).catch(err=>{
                        this.setError('detailed')
                        reject(err)
                    })
                }).catch(err=>{
                    this.setError('detailed')
                    reject(err)
                })
            })
        },
        async exas (arg) {
            const requestFn = () => {
                return []
            }
            exas(arg, this, requestFn)
        },
        //保存全部数据
        saveAll () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateBudgetDtl(),

                ]
            }
            saveAll(this, requestFn)
        },
        submitCommit () {
            const requestFn = ()=>{
                return [
                    this.updateBaseInfo(),
                    this.updateBudgetDtl(),
                ]
            }
            submitCommit(this, requestFn)
        },

        //刷新历史审核列表
        getAuditHistory () {
            this.$refs.AuditHistoryRef.auditHistory()
        },
        //点击删除
        clickDel () {
            this.clientPop(
                'info',
                '确定要删除吗？删除的数据可以在【回收站】还原或彻底删除。',
                this.delData
            )
        },
        delData () {
            showLoading()

            this.$Ajax
                .httpGet({
                    url: '/turnover/procurementPlan/delete',
                    params: { billId: this.id },
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    }
                })
                .then(() => {
                    hideLoading()

                    this.clientPop('suc', '删除成功', this.handleClose)
                })
        },

        handleClose () {
            this.$router.replace('/procuremenPlanList')
        },
        //点击删除的时候
        deleteEle (row, $index) {
            this.clientPop(
                'info',
                this.oneDeleteErr,
                () => {
                    deleteLogic(row, $index, this, ['amountExcludingTax', 'taxAmount', 'amount'])
                }
            )
        },
        // 处理树
        tableRowClassName ({ row }) {
            if (row.children) {
                return 'warning-row'
            }else if(row.changeType === -1) {
                return  'row-hide'
            }else{
                return  'row-show'
            }
        },
        //设置错误标签
        setError (name) {
            if (!this.errorList.find(x => x === name)) {
                this.errorList.push(name)
            }
        },
        //跳转到第一个错误标签
        scorllError () {
            let num = this.tabArr.length
            this.errorList.forEach(item => {
                let index = this.tabArr.findIndex(x => x === item)
                num = index < num ? index : num
            })
            const obj = { name: this.tabArr[num] }
            this.tabsName = this.tabArr[num]
            this.onChangeTab(obj)
        },
        //计划明细非空验证
        verifyTable () {
            return new Promise((resolve, reject)=>{
                this.errorMsg = []

                if(this.detailedTableData.length > 0) {

                    this.detailedTableData.forEach(v => {
                        v.children.forEach((item, index) => {
                            if (item.changeType !== -1) {

                                if (item.quantity == '' || item.quantity == null) {
                                    let str = `请填写第 ${index + 1} 行的需求数量`
                                    this.errorMsg.push(str)
                                }
                                if (item.price == '' || item.price == null) {
                                    let str = `请填写第 ${index + 1} 行的单价`
                                    this.errorMsg.push(str)
                                }
                                if (item.startTime == '' || item.startTime == null) {
                                    let str = `请填写第 ${index + 1} 行的进场时间`
                                    this.errorMsg.push(str)
                                }
                            }
                        })
                    })

                }
                if (this.errorMsg.length > 0) {
                    this.isErrorMsg = true
                    reject()

                } else {
                    this.isErrorMsg = false
                    resolve()

                }

            })

        },
        /**变更历史 */
        //点击查看的时候
        toChengePlanAdd () {
            this.$router.push('/procuremenPlanChengeAdd')
        },
        clickEdit (billid) {
            this.$router.push({ path: '/procuremenPlanChengeEdit', query: { billid } })
        },
        cellMouseEnter (row) {
            this.MouseEnterId = row.id
        },
        cellMouseLeave () {
            this.MouseEnterId = 0
        },
        //点击进入修改页面
        tableDbShow (row, column) {
            const billid = row.billId
            if (column.label === '计划编号') {
                this.$router.push({ path: '/procuremenPlanChengeShow', query: { billid } })
            }
        },
    }
}
</script>

<style lang="scss" scoped>
.e-table {
    min-height: auto;
    background: #fff;
}
.upload {
    margin: 20px auto;
    display: flex;
    justify-content: center;
    text-align: center;
}

.upload-demo {
    display: flex;
    justify-content: center;
    align-items: center;
}

::v-deep.el-input--suffix .el-input__inner {
    padding-right: 5px;
}
::v-deep.el-table .cell {
    text-align: center;
}
#iconEdit:hover {
  color: red;
}

.like {
  color: rgb(46, 97, 215);
  font-size: 17px;
  line-height: 30px;
  cursor: pointer;
}
</style>
